package com.tantou.leetcode.easy;

import java.util.Arrays;

/**
 * @author jiangweiyang
 * @created 2020/4/29 21:54
 **/
public class RemoveElement {

    /**
     * https://leetcode-cn.com/problems/remove-element/
     * @param args
     */
    public static void main(String[] args) {
        int[] nums = new int[]{3,2,2,3};
//        int result = remove(nums, 3);
//        System.out.println(Arrays.toString(nums));

        int result2 = remove2(nums, 3);
        System.out.println(Arrays.toString(nums));
        int a = 2;
    }

    public static int remove(int[] nums, int val) {
        int i = 0;
        for (int k = 0; k < nums.length; k++) {
            //如果当前数与目标数想等，则代表这个数是需要移除的
            if (nums[k] != val) {
                nums[i] = nums[k];
                i++;
            }
        }
        return i;
    }

    public static int remove2(int[] nums, int val) {
        int len = nums.length;
        for (int i = 0; i < len; ) {
            if (nums[i] == val) {
                nums[i] = nums[len - 1];
                len--;
            } else {
                i++;
            }
        }
        return len;
    }
}
